import { Tile } from "ol/layer";
import {
  XYZ,
  Stamen,
  TileArcGISRest as ArcgisSource,
} from "ol/source";

export class MapEnum {
  static get Street() {
    return 'street';
  }
  static get WaterColor() {
    return 'waterColor';
  }
  static get Satellite() {
    return 'satellite';
  }
  static get Maphoto() {
    return 'maphoto';
  }
  static get Label() {
    return 'label';
  }
}

const tk = 'bdbf8bbd2d00a2731397dca87a489db0';

/**
 * @description 添加图层
 * @export
 * @param {String} name 图层名称（类型）
 * @return {Promise}
 */
export function layerAdd(name) {
  switch (name) {
    case MapEnum.Satellite:
      return new Tile({
        name: name,
        zIndex: 99,
        source: new ArcgisSource({
          url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer',
        }),
      });
    case MapEnum.Street:
      return new Tile({
        name: name,
        zIndex: 99,
        source: new XYZ({
          url: 'https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
        }),
      });
    case MapEnum.WaterColor:
      return new Tile({
        name: name,
        zIndex: 99,
        source: new Stamen({
          layer: 'watercolor',
        }),
      });
    case MapEnum.Label:
      return new Tile({
        zIndex: 98,
        name: name,
        source: new XYZ({
          url: 'http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=' + tk,
        }),
      });
    default:
      break;
  }
}

/**
 * @description
 * @export
 * @param {Array<String>} names 操作的图层名称
 * @param {boolean} [reverse=false] 是否反转
 */
export function layerRemove(names, reverse = false) {
  let map = window.map;
  const layers = map.getAllLayers();
  layers.forEach(lyr => {
    if (names.find(item => item === lyr.getProperties().name)) {
      if (!reverse) map.removeLayer(lyr);
    } else {
      if (reverse) map.removeLayer(lyr);
    }
  });
}

/**
 * @description 切换地图
 * @export
 * @param {String} type 图层类型（名称）
 */
export function layerChange(type) {
  let map = window.map;
  switch (type) {
    case MapEnum.Street:
      layerRemove([MapEnum.Maphoto], true);
      map.addLayer(layerAdd(type));
      break;
    case MapEnum.WaterColor:
      layerRemove([MapEnum.Maphoto], true);
      map.addLayer(layerAdd(type));
      break;

    case MapEnum.Satellite:
      layerRemove([MapEnum.Maphoto], true);
      map.addLayer(layerAdd(MapEnum.Label));
      map.addLayer(layerAdd(type));
      break;
  }
}
